package designpatterns.produceconsume;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 李栋
 * @version 1.0.0
 * @className WaitNotiFyTest.java
 * @createTime 2021年08月07日 19:36:00
 */
public class WaitNotiFyTest {

    private static final Logger logger = LoggerFactory.getLogger(WaitNotiFyTest.class);


    private static Integer count = 0;
    private static final Integer FULL = 5;
    private static final String LOCK = "lock";


    public static void main(String[] args) {
        WaitNotiFyTest waitNotiFyTest = new WaitNotiFyTest();
        new Thread(new ProducerRunnable()).start();
        new Thread(waitNotiFyTest.new ConsumerRunnable()).start();
        new Thread(new ProducerRunnable()).start();
        new Thread(waitNotiFyTest.new ConsumerRunnable()).start();
        new Thread(new ProducerRunnable()).start();
        new Thread(waitNotiFyTest.new ConsumerRunnable()).start();
    }

    static class ProducerRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (Exception e) {
                    logger.error(e.getMessage(),e);
                }
                synchronized (LOCK) {
                    while (count.equals(FULL)) {
                        try {
                            LOCK.wait();
                        } catch (Exception e) {
                            logger.error(e.getMessage(),e);
                        }
                    }
                    count++;
                    logger.info(Thread.currentThread().getName() + "生产者生产，目前总共有" + count);
                    LOCK.notifyAll();
                }
            }
        }
    }

    class ConsumerRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(),e);
                }
                synchronized (LOCK) {
                    while (count == 0) {
                        try {
                            LOCK.wait();
                        } catch (Exception e) {
                        }
                    }
                    count--;
                    logger.info(Thread.currentThread().getName() + "消费者消费，目前总共有" + count);
                    LOCK.notifyAll();
                }
            }
        }
    }

}

